package cn.dengta.webapp.trade.entity.meta;

import java.util.Map;

import cn.dengta.context.model.WesKit;
import cn.dengta.webapp.trade.entity.meta.MetaConfig.MetaRuleConfig;
import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.*;

/**
 * 缘分雷达规则配置
 */
@Getter
@Setter
public class SpeedDatingRule implements MetaRuleConfig {

	/** 男用户接收速配频率周期（分钟） */
	protected int maleOutsidePeriod;
	/** 男用户接收速配频率次数（次） */
	protected int maleMaxTimesInPeriod;
	/** 女用户接收速配频率周期（分钟） */
	protected int femaleOutsidePeriod;
	/** 女用户接收速配频率次数（次） */
	protected int femaleMaxTimesInPeriod;

	/** VIP推荐是否优先匹配 */
	protected boolean vipRecFirst = true;
	/** 普通推荐是否优先匹配 */
	protected boolean recFirst = true;

	/** 生效包：-1=全部；逗号分隔 */
	private String wesKit = "-1";

	/** 免费配置 */
	private Map<WesKit, FreeConfig> freeConfig;

	public FreeConfig findFree(WesKit wesKit) {
		return X.isValid(freeConfig) ? freeConfig.get(wesKit) : new FreeConfig();
	}

	@Override
	public void validate() {
		Assert.isTrue(maleOutsidePeriod > 0, "男用户接收速配频率周期必须大于0！");
		Assert.isTrue(maleMaxTimesInPeriod >= 0, "男用户接收速配频率次数不能小于0！");
		Assert.isTrue(femaleOutsidePeriod > 0, "女用户接收速配频率周期必须大于0！");
		Assert.isTrue(femaleMaxTimesInPeriod >= 0, "女用户接收速配频率次数不能小于0！");
	}

	@Override
	public void init(MetaRuleConfig config) {
		SpeedDatingRule cfg = (SpeedDatingRule) config;
		this.maleOutsidePeriod = cfg.maleOutsidePeriod;
		this.maleMaxTimesInPeriod = cfg.maleMaxTimesInPeriod;
		this.femaleOutsidePeriod = cfg.femaleOutsidePeriod;
		this.femaleMaxTimesInPeriod = cfg.femaleMaxTimesInPeriod;
		this.freeConfig = cfg.getFreeConfig();
	}

	public int maxTimesInPeriod(final boolean male) {
		return male ? maleMaxTimesInPeriod : femaleMaxTimesInPeriod;
	}

	public int outsidePeriod(final boolean male) {
		return male ? maleOutsidePeriod : femaleOutsidePeriod;
	}

	/**
	 * 免费配置
	 */
	@Getter
	@Setter
	public static class FreeConfig {

		/** 视频免费次数 */
		private Integer videoTimes = 0;
		/** 单次免费时长(分钟) */
		private Integer freeDuration = 0;

		public Integer getFreeDurationSecs() {
			return this.freeDuration * 60;
		}

		public boolean validValue(Long userId) {
			return Cmp.gt(videoTimes, 0) && Cmp.gt(freeDuration, 0);
		}

	}

}
